﻿#include <winsock2.h>
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9999
#define BUF_SIZE 1024
void Error(const string &msg)
{
  cout << msg << endl;
  exit(-1);
}
int main()
{
  WSADATA wsadata;
  WSAStartup(MAKEWORD(2, 2), &wsadata);
  // step01:创建客户端socket套接字
  SOCKET sock_clnt;
  if ((sock_clnt = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
    Error("socket() error!");

  // step02：连接客户端套接字与服务端套接字
  sockaddr_in addr_serv{};
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.S_un.S_addr = inet_addr(SERVER_IP);
  addr_serv.sin_port = htons(SERVER_PORT);
  if (connect(sock_clnt, (sockaddr *)&addr_serv, sizeof(addr_serv)) == -1)
    Error("connect() error!");
  // step03:传输数据
  string msg;
  char response[BUF_SIZE];
  while (1)
  {
    cout << "Please input message:";
    cin >> msg;
    if (msg == "q" || msg == "Q")
      break;
    send(sock_clnt, msg.c_str(), sizeof(msg), 0);
    recv(sock_clnt, response, sizeof(response), 0);
    cout << "Response from server:" << response << endl;
  }

  closesocket(sock_clnt);
  WSACleanup();
  return 0;
}